//
//  HLEditInfoViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/5/19.
//

#import "HLEditInfoViewController.h"

#import "HLOSSManager.h"
#import "HLEditInfoRequest.h"

#import "HLEditSignatureViewController.h"
#import "HLEditNicknameViewController.h"
#import "HLMineCell.h"
#import "HLEditAvatarCell.h"
#import "HLEditPhotoWallCell.h"
#import "HLEditSignatureCell.h"

@interface HLEditInfoViewController ()

@property (nonatomic, copy) HLCommonCallback callback;
@property (nonatomic, strong) HLUserInfoModel *userModel;
@property (nonatomic, strong) HLOSSManager *avatarOSSManager;
@property (nonatomic, strong) HLOSSManager *photoWallOSSManager;

@end

@implementation HLEditInfoViewController

- (instancetype)initWithModel:(HLUserInfoModel *)userModel callback:(nonnull HLCommonCallback)callback
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self){
        self.callback = callback;
        self.userModel = [HLUserInfoModel mj_objectWithKeyValues:[userModel mj_JSONObject]];
        self.avatarOSSManager = [[HLOSSManager alloc] initWithOSSPath:@"avatar"];
        self.photoWallOSSManager = [[HLOSSManager alloc] initWithOSSPath:@"photoWall"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HLBackgroundColor;
    if ([self.userModel.editUserOpuses isEqualToString:@"1"]){
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:4];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
    }
    if (self.userModel.userOpuses.count > 0){
        self.userModel.userOpuseUrlsChangeState = @"1";
    }
}

- (void)setupNavigationItems
{
    [super setupNavigationItems];
    self.title = @"编辑资料";
    
    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithCustomView:({
        QMUIButton *saveButton = [[QMUIButton alloc] init];
        [saveButton setTitle:@"保存" forState:UIControlStateNormal];
        [saveButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
        [saveButton.titleLabel setFont:UIFontMediumMake(12)];
        [saveButton setBackgroundColor:HLMainColor];
        [saveButton setContentEdgeInsets:UIEdgeInsetsMake(6, 12, 6, 12)];
        saveButton.cornerRadius = 14;
        [saveButton addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
        saveButton;
    })];
    
    self.navigationItem.rightBarButtonItem = saveItem;
}

- (void)initTableView
{
    [super initTableView];
    
    self.tableView.backgroundColor = HLBackgroundColor;
    [self.tableView registerClass:[HLMineCell class] forCellReuseIdentifier:[HLMineCell identifyCell]];
    [self.tableView registerClass:[HLEditAvatarCell class] forCellReuseIdentifier:[HLEditAvatarCell identifyCell]];
    [self.tableView registerClass:[HLEditPhotoWallCell class] forCellReuseIdentifier:[HLEditPhotoWallCell identifyCell]];
    [self.tableView registerClass:[HLEditSignatureCell class] forCellReuseIdentifier:[HLEditSignatureCell identifyCell]];
    
    [self updateUserInfo];
}

- (void)updateUserInfo
{
    [self.datasources removeAllObjects];
    [self.datasources addObjectsFromArray:[HLMineCellModel cellWithEditInfoWithModel:self.userModel]];
    [self.tableView reloadData];
}

- (void)saveAction
{
    if (self.userModel.avatarImage){
        MJWeakSelf;
        [self.avatarOSSManager uploadDatas:@[self.userModel.avatarImage] callBack:^(NSArray<NSString *> * urls) {
            weakSelf.userModel.avatar = [urls firstObject];
            weakSelf.userModel.avatarImage = nil;
            [weakSelf saveAction];
        }];
    } else if ([self.userModel.userOpuseUrlsChangeState boolValue]){
        NSMutableArray *opus = [NSMutableArray array];
        for (HLOpusModel *opusM in self.userModel.userOpuses) {
            [opus addObject:opusM.opusLink];
        }
        self.userModel.photoUrlList = opus;
        self.userModel.userOpuseUrlsChangeState = nil;
        [self saveAction];
    } else if (self.userModel.userOpuseImages.count > 0){
        MJWeakSelf
        [self.photoWallOSSManager uploadDatas:self.userModel.userOpuseImages callBack:^(NSArray<NSString *> *urls) {
            NSArray *photoUrlList = [NSArray array];
            if (weakSelf.userModel.photoUrlList.count > 0){
                photoUrlList = weakSelf.userModel.photoUrlList;
            }
            NSMutableArray *opus = [NSMutableArray arrayWithArray:photoUrlList];
            for (NSString *url in urls) {
                [opus addObject:url];
            }
            weakSelf.userModel.userOpuseImages = nil;
            weakSelf.userModel.photoUrlList = opus;
            [weakSelf saveAction];
        }];
    } else {
        [QMUITips hideAllTips];
        [QMUITips showLoading:@"保存中..." inView:[HLUIHelper keyWindow]];
        [self.userModel resetLocal];
        NSDictionary *editInfo = [self.userModel mj_JSONObject];
        self.request = [[HLEditInfoRequest alloc] initWithEditInfo:editInfo];
        self.request.delegate = self;
        [self.request start];
    }
}


- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDarkContent;
}

- (UIImage *)qmui_navigationBarBackgroundImage
{
    return [UIImage qmui_imageWithColor:HLBackgroundColor];
}

- (nullable UIColor *)qmui_navigationBarTintColor
{
    return UIColorBlack;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datasources.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sections = self.datasources[section];
    return sections.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HLMineCellModel *cellModel = self.datasources[indexPath.section][indexPath.row];
    
    if (cellModel.cellSpot == HLMineCellSpotEditAvatar){
        HLEditAvatarCell *cell = [tableView dequeueReusableCellWithIdentifier:[HLEditAvatarCell identifyCell]];
        cell.model = self.userModel;
        return cell;
    } else if (cellModel.cellSpot == HLMineCellSpotEditPhotoWall){
        HLEditPhotoWallCell *cell = [tableView dequeueReusableCellWithIdentifier:[HLEditPhotoWallCell identifyCell]];
        cell.model = self.userModel;
        return cell;
    } else if (cellModel.cellSpot == HLMineCellSpotEditSignature){
        HLEditSignatureCell *cell = [tableView dequeueReusableCellWithIdentifier:[HLEditSignatureCell identifyCell]];
        cell.model = self.userModel;
        return cell;
    } else {
        HLMineCell *cell = [tableView dequeueReusableCellWithIdentifier:[HLMineCell identifyCell]];
        cell.model = cellModel;
        return cell;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = UIColorWhite;
    
    HLMineCellModel *cellModel = self.datasources[section][0];
    if (cellModel.cellSpot == HLMineCellSpotEditNickname){
        QMUILabel *titleLabel = [[QMUILabel alloc] init];
        titleLabel.font = UIFontMediumMake(13);
        titleLabel.textColor = HLTextColor3;
        titleLabel.text = @"关于我";
        [footerView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.mas_equalTo(12);
        }];
    }
    
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    HLMineCellModel *cellModel = self.datasources[section][0];
    if (cellModel.cellSpot == HLMineCellSpotEditNickname){
        return 42;
    } else if (section == 0){
        return 0;
    } else {
        return 12;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLMineCellModel *model = self.datasources[indexPath.section][indexPath.row];
    MJWeakSelf;
    switch (model.cellSpot) {
        case HLMineCellSpotEditSignature:
        {
            HLEditSignatureViewController *signatureVC = [[HLEditSignatureViewController alloc] initWithSignature:self.userModel.selfSign callback:^(NSString * signature) {
                weakSelf.userModel.selfSign = signature;
                [weakSelf updateUserInfo];
            }];
            [self.navigationController pushViewController:signatureVC animated:YES];
        }
            break;
        case HLMineCellSpotEditNickname:
        {
            HLEditNicknameViewController *nicknameVC = [[HLEditNicknameViewController alloc] initWithNickname:self.userModel.nickName callback:^(NSString * nickname) {
                weakSelf.userModel.nickName = nickname;
                [weakSelf updateUserInfo];
            }];
            [self.navigationController pushViewController:nicknameVC animated:YES];
        }
            break;
        
        default:
            break;
    }
}


-(void)requestFinished:(__kindof YTKBaseRequest *)request
{
    [QMUITips hideAllTips];
   [super requestFinished:request];
    HLEditInfoRequest *editRequest = (HLEditInfoRequest *)request;
    if (editRequest.isSuccess){
        if (self.callback){
            self.callback(self.userModel);
        }
       [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request
{
    [QMUITips hideAllTips];
   [super requestFailed:request];
}



@end
